<template>
  <div class="file-explorer-button">
    <ElButton size="mini" icon="el-icon-plus" type="primary" @click="createFolder">新建</ElButton>
    <!--创建文件夹对话框-->
    <CreateFolderDialog
      v-if="createFolderDialogVisible"
      v-bind="explorer.createFolderParams"
      :visible.sync="createFolderDialogVisible"
      :parent-id="explorer.folder.id"
      @create-folder-success="createFolderSuccess" />
  </div>
</template>

<script>
  import CreateFolderDialog from '@/components/x-file-explorer-lite/plugins/CreateFolderDialog'

  export default {
    name: 'CreateFileButton',
    components: { CreateFolderDialog },
    inject: ['explorer'],
    data() {
      return {
        createFolderDialogVisible: false
      }
    },
    methods: {
      async createFolder() {
        const { explorer } = this
        if (explorer.nameEditMode === 'inline') {
          const newFolder = {
            id: -1,
            [explorer.nameProp]: '新建文件夹',
            edit: true,
            fileType: 'folder'
          }

          if (explorer.$refs.tree) {
            const nodes = explorer.$refs.tree.$refs.etTree.findTreeNode(explorer.folder.id)
            if (nodes && nodes.length) {
              explorer.$refs.tree.$refs.etTree.appendChildNodeWithData(
                nodes[0],
                explorer.folder.id,
                newFolder[explorer.nameProp]
              )
            } else {
              await explorer.$refs.tree.$refs.etTree.addRootNode({ ...newFolder, edit: false })
            }
          }

          explorer.files.unshift(newFolder)
          explorer.currentRow = newFolder
          explorer.rename()
        } else {
          this.createFolderDialogVisible = true
        }
      },
      async createFolderSuccess(res) {
        const { explorer } = this
        const newFolder = {
          id: res.data.id,
          parentId: res.data.parentId,
          [explorer.nameProp]: res.data.folderName,
          fileType: 'folder'
        }

        if (explorer.$refs.tree) {
          const nodes = explorer.$refs.tree.$refs.etTree.findTreeNode(explorer.folder.id)
          if (nodes && nodes.length) {
            explorer.$refs.tree.$refs.etTree.appendChildNodeWithData(
              nodes[0],
              explorer.folder.id,
              newFolder[explorer.nameProp]
            )
          } else {
            await explorer.$refs.tree.$refs.etTree.addRootNode({ ...newFolder, edit: false })
          }
        }
        explorer.files.unshift(newFolder)
      }
    }
  }
</script>
